import { defineComponent, reactive, computed, ref, toRaw } from 'vue'
import FlowCard from './components/FlowCard/index'
import { NodeUtils, getMockFlowData } from './flow'
import conf from './mockData'
import './index.scss'
import BpmnModdle from 'bpmn-moddle'
import template from './template'
const { initTemplate } = template

export default defineComponent({
  setup() {
    const _data = getMockFlowData()
    if (typeof conf === 'object') {
      Object.assign(_data, conf)
    }
    const data = ref(_data)
    const state = reactive({
      // 缩放比例 100%
      scale: 100,
      // 缩放步长
      step: 10,
      // key值 用于模拟$forceUpdate
      updateId: 0,
      // 被激活的流程卡片数据，用于属性面板编辑
      activeData: null,
      verifyMode: false
    })

    const scaleStyle = computed(() => ({ transform: `scale(${state.scale / 100})` }))

    function changeScale(val) {
      state.scale = Math.max(50, Math.min(300, state.scale + val))
    }

    function eventReceiver({ event, args }) {
      if (event === 'edit') {
        return
      }
      NodeUtils[event](...args)
      forceUpdate()
    }

    function forceUpdate() {
      state.updateId++
    }

    const flowCardRef = ref(null)
    function flowCardInstance() {}

    function getData() {
      console.log(toRaw(data.value))
    }

    function handleTest() {}

    const moddle = new BpmnModdle()

    async function formXml(xml) {
      const res = await moddle.fromXML(xml)
      console.log(res)
    }

    function readXml() {
      const xml = initTemplate()
      formXml(xml)
    }

    return () => {
      return (
        <div class="flow-page">
          <div class="zoom">
            <div class="ifont-minus zoom-out" onClick={() => changeScale(-state.step)}></div>
            <span>{state.scale}%</span>
            <div class="ifont-plus zoom-in" onClick={() => changeScale(state.step)}></div>
          </div>
          <div class="fixed-edit-group">
            <a-button onClick={getData}>获取数据</a-button>
            <a-button onClick={handleTest}>暂定</a-button>
            <a-button onClick={readXml}>读取xml</a-button>
          </div>
          <FlowCard
            ref={flowCardRef}
            key={state.updateId}
            verifyMode={state.verifyMode}
            data={data.value}
            onEmits={eventReceiver}
            style={scaleStyle.value}
          />
        </div>
      )
    }
  }
})
